/**
 * 
 */
package com.pmsco.pms.business;

import java.util.Calendar;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pmsco.pms.business.dto.PmsUserRequestDTO;
import com.pmsco.pms.business.dto.PmsUserReturnDTO;
import com.pmsco.pms.core.constant.PmsConstant;
import com.pmsco.pms.core.domain.PmsRole;
import com.pmsco.pms.core.domain.PmsUser;
import com.pmsco.pms.services.impl.PmsRoleServiceImpl;
import com.pmsco.pms.services.impl.PmsUserServiceImpl;
import com.pmsco.pms.services.interfaces.PmsRoleService;
import com.pmsco.pms.services.interfaces.PmsUserService;
import com.pmsco.pms.util.PmsMailSender;
import com.pmsco.pms.util.PmsSysInfo;
import com.pmsco.pms.util.PmsUserRole;

/**
 * @author Long Tran
 *
 */
public class PmsUserBusiness {
	private static final Logger logger = LoggerFactory.getLogger(PmsUserBusiness.class);
	private PmsUserService pmsUserService = new PmsUserServiceImpl();
	private PmsRoleService pmsRoleService = new PmsRoleServiceImpl();
	
	public PmsUserReturnDTO listUserData(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start listUserData");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		List<PmsUser> pmsUsers = pmsUserService.listPmsUser(pmsUserRequestDTO.getSearchField(), 
				pmsUserRequestDTO.getSearchString(), 
				pmsUserRequestDTO.getSearchOper(), 
				pmsUserRequestDTO.getSidx(), 
				pmsUserRequestDTO.getSord(), 
				pmsUserRequestDTO.getPage(), 
				pmsUserRequestDTO.getRows());
		
		Integer pmsUsersSize = pmsUserService.countListPmsUser(pmsUserRequestDTO.getSearchField(), 
				pmsUserRequestDTO.getSearchString(), 
				pmsUserRequestDTO.getSearchOper());
		
		pmsUserReturnDTO.setPmsUsers(pmsUsers);
		pmsUserReturnDTO.setPmsUsersSize(pmsUsersSize);
		
		logger.info("End listUserData");
		return pmsUserReturnDTO;
	}
	
	public PmsUserReturnDTO createUser(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start createUser");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		pmsUserReturnDTO.setPmsUser(new PmsUser());
		pmsUserReturnDTO.setRoleList(pmsRoleService.listPmsRole(new PmsRole()));
		pmsUserReturnDTO.setReturnView(PmsConstant.createUser_View);
		
		logger.info("End createUser");
		return pmsUserReturnDTO;
	}
	
	public PmsUserReturnDTO editUser(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start editUser");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		pmsUserReturnDTO.setPmsUser(pmsUserService.loadPmsUserByName(pmsUserRequestDTO.getUserName()));
		pmsUserReturnDTO.setRoleList(pmsRoleService.listPmsRole(new PmsRole()));
		pmsUserReturnDTO.setReturnView(PmsConstant.editUser_View);
		
		logger.info("End editUser");
		return pmsUserReturnDTO;
	}
	
	public PmsUserReturnDTO saveUser(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start saveUser");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		logger.debug("Check if user name existed");
		PmsUser userDetail = pmsUserRequestDTO.getPmsUser();
		PmsUser existedUser = pmsUserService.loadPmsUserByName(userDetail.getUserName());
		
		logger.debug("User name: " + userDetail.getUserName());
		logger.debug("Id: " + String.valueOf(userDetail.getId()));
		if((existedUser != null && userDetail.getId() == null) || (existedUser != null && existedUser.getId().compareTo(userDetail.getId()) != 0)) {
			pmsUserReturnDTO.setReturnView(PmsConstant.editUser_View);
			pmsUserReturnDTO.setPmsUser(userDetail);
			pmsUserReturnDTO.setRoleList(pmsRoleService.listPmsRole(new PmsRole()));
			pmsUserReturnDTO.setErrorMessage(PmsConstant.userName_Existed_Key);
		} else {
			logger.debug("Check if email address existed");
			existedUser = pmsUserService.loadPmsUserByEmail(userDetail.getEmailAddr());
			
			logger.debug("User name: " + userDetail.getUserName());
			logger.debug("Id: " + String.valueOf(userDetail.getId()));
			if((existedUser != null && userDetail.getId() == null) || (existedUser != null && existedUser.getId().compareTo(userDetail.getId()) != 0)) {
				pmsUserReturnDTO.setReturnView(PmsConstant.editUser_View);
				pmsUserReturnDTO.setPmsUser(userDetail);
				pmsUserReturnDTO.setRoleList(pmsRoleService.listPmsRole(new PmsRole()));
				pmsUserReturnDTO.setErrorMessage(PmsConstant.userEmail_Existed_Admin_Key);
			} else {
				PmsRole role = pmsRoleService.getRoleById(pmsUserRequestDTO.getRoleId());
				userDetail.setPmsRole(role);
				if(existedUser == null) {
					userDetail.setRegisterDate(Calendar.getInstance().getTime());
					userDetail.setActivated(PmsConstant.UserUnActivate);
					userDetail.setFailLogonCount(PmsConstant.DefaultLogonFailCount);
					userDetail.setLocked(PmsConstant.UserUnLock);
				} else {
					userDetail.setRegisterDate(existedUser.getRegisterDate());
					userDetail.setActivated(existedUser.getActivated());
					userDetail.setFailLogonCount(existedUser.getFailLogonCount());
					userDetail.setLastLogonDate(existedUser.getLastLogonDate());
					userDetail.setLocked(existedUser.getLocked());
				}
				pmsUserService.saveOrUpdatePmsUser(userDetail);
				
				if(existedUser == null) {
					logger.debug("Send email save user success");
					String emailMessage = pmsUserRequestDTO.getEmailBody();
					emailMessage = emailMessage.replace("$1", userDetail.getUserName());
					emailMessage = emailMessage.replace("$2", "?ref=" + PmsSysInfo.getInstance().getPmsEncoder().encode(userDetail.getUserName()));
					PmsMailSender.getInstance().sendMail("noreply.pmssystem@gmail.com", userDetail.getEmailAddr(), pmsUserRequestDTO.getEmailSubject(), emailMessage);
				}
				
				pmsUserReturnDTO.setReturnUrl(PmsConstant.listUser_JspUrl);
			}
		}
		
		logger.info("End saveUser");
		return pmsUserReturnDTO;
	}
	
	public PmsUserReturnDTO doRegisterUser(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start doRegisterUser");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		logger.debug("Check if user name existed");
		PmsUser userDetail = pmsUserRequestDTO.getPmsUser();
		PmsUser existedUser = pmsUserService.loadPmsUserByName(userDetail.getUserName());
		
		logger.debug("User name: " + userDetail.getUserName());
		logger.debug("Id: " + String.valueOf(userDetail.getId()));
		if((existedUser != null && userDetail.getId() == null) || (existedUser != null && existedUser.getId().compareTo(userDetail.getId()) != 0)) {
			pmsUserReturnDTO.setReturnView(PmsConstant.registerUser_View);
			pmsUserReturnDTO.setPmsUser(userDetail);
			pmsUserReturnDTO.setRoleList(pmsRoleService.listPmsRole(new PmsRole()));
			pmsUserReturnDTO.setErrorMessage(PmsConstant.userName_Existed_Key);
		} else {
			logger.debug("Check if email address existed");
			existedUser = pmsUserService.loadPmsUserByEmail(userDetail.getEmailAddr());
			
			logger.debug("User name: " + userDetail.getUserName());
			logger.debug("Id: " + String.valueOf(userDetail.getId()));
			if((existedUser != null && userDetail.getId() == null) || (existedUser != null && existedUser.getId().compareTo(userDetail.getId()) != 0)) {
				pmsUserReturnDTO.setReturnView(PmsConstant.registerUser_View);
				pmsUserReturnDTO.setPmsUser(userDetail);
				pmsUserReturnDTO.setRoleList(pmsRoleService.listPmsRole(new PmsRole()));
				pmsUserReturnDTO.setErrorMessage(PmsConstant.userEmail_Existed_Key);
			} else {
				PmsRole role = pmsRoleService.getRole(PmsUserRole.NORMAL_USER.getRole());
				userDetail.setPmsRole(role);
				userDetail.setRegisterDate(Calendar.getInstance().getTime());
				userDetail.setActivated(PmsConstant.UserUnActivate);
				userDetail.setFailLogonCount(PmsConstant.DefaultLogonFailCount);
				userDetail.setLocked(PmsConstant.UserUnLock);
				pmsUserService.saveOrUpdatePmsUser(userDetail);
				
				logger.debug("Send email save user success");
				String emailMessage = pmsUserRequestDTO.getEmailBody();
				emailMessage = emailMessage.replace("$1", userDetail.getUserName());
				emailMessage = emailMessage.replace("$2", "?ref=" + PmsSysInfo.getInstance().getPmsEncoder().encode(userDetail.getUserName()));
				PmsMailSender.getInstance().sendMail("noreply.pmssystem@gmail.com", userDetail.getEmailAddr(), pmsUserRequestDTO.getEmailSubject(), emailMessage);
				
				pmsUserReturnDTO.setReturnUrl(PmsConstant.registerUserSuccessful_JspUrl);
			}
		}
		
		logger.info("End doRegisterUser");
		return pmsUserReturnDTO;
	}
	
	public PmsUserReturnDTO activateUser(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start activateUser");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		PmsUser userDetail = pmsUserService.loadPmsUserByName(pmsUserRequestDTO.getUserName());
		if(userDetail != null) {
			userDetail.setActivated(PmsConstant.UserActivated);
			pmsUserService.saveOrUpdatePmsUser(userDetail);
			pmsUserReturnDTO.setReturnView(PmsConstant.activateUser_View);
		} else {
			pmsUserReturnDTO.setReturnView(PmsConstant.failActivateUser_View);
		}
		
		logger.info("End activateUser");
		return pmsUserReturnDTO;
	}
	
	public PmsUserReturnDTO unlockUser(PmsUserRequestDTO pmsUserRequestDTO) {
		logger.info("Start unlockUser");
		PmsUserReturnDTO pmsUserReturnDTO = new PmsUserReturnDTO();
		
		PmsUser userDetail = pmsUserService.loadPmsUserByName(pmsUserRequestDTO.getUserName());
		if(userDetail != null) {
			userDetail.setLocked(PmsConstant.UserUnLock);
			userDetail.setFailLogonCount(new Integer(0));
			pmsUserService.saveOrUpdatePmsUser(userDetail);
			pmsUserReturnDTO.setReturnView(PmsConstant.unlockUser_View);
		} else {
			pmsUserReturnDTO.setReturnView(PmsConstant.failUnlockUser_View);
		}
		
		logger.info("End unlockUser");
		return pmsUserReturnDTO;
	}
}
